/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.util.ArrayList;
import java.util.List;
import model.Fag;
import model.Hold;
import model.HoldFag;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

public class FagHandler {

    private Session session;
    
    public FagHandler(Session session){
        this.session = session;
    }
    
  
    public Fag[] hentFag() throws HibernateException {

        String hql = "from Fag";
        session.beginTransaction();
        Query q = session.createQuery(hql);
        List resultList = q.list();
        Fag[] fagene = new Fag[resultList.size()];
        for (int i = 0; i < resultList.size(); i++) {

            fagene[i] = (Fag) resultList.get(i);
        }
        session.getTransaction().commit();
        return fagene;
    }    
    
    public void nytFag(Fag fag) throws HibernateException {
                
        session.beginTransaction();
        String hql = "from Fag";
        session.flush();
        session.createQuery(hql);
        session.save(fag);
        session.getTransaction().commit();
    }
//
    public Fag[] hentFagIkkeHold(Hold h) throws HibernateException {
        String hql = "from Fag";
        session.beginTransaction();
        Query q = session.createQuery(hql);
        List resultList = q.list();
        ArrayList<Fag> fagene = new ArrayList<Fag>();
        for (int i = 0; i < resultList.size(); i++) {
           fagene.add((Fag) resultList.get(i));
        }
        
        session.getTransaction().commit();
        
        Object[] obarr = h.getHoldFags().toArray();
        
        for (int i = 0; i < obarr.length; i++) {

            HoldFag f = (HoldFag) obarr[i];
            
            fagene.remove(f.getFag());
            
        }
        Object[] arr = fagene.toArray();
        Fag[] f = new Fag[arr.length];
        for (int i = 0; i < arr.length; i++) {
            f[i] = (Fag) arr[i];
            
        }
        return f;
    }
    
        
}
